<template>
    <div style="height:1500px;">
        
        <el-card shadow="never">
            <div class="title">商品信息</div>
            <div style="height: 280px;">
                <p class="info">商品主图</p>
                <div style="float:left;width:600px;">
                        <div style="margin-bottom: 20px;">只能上传一张尺寸为256*256的图片，大小为150K以内,支持jpg,jpeg,bmp,png,gif格式</div>
                        <el-upload
                      
                        ref="mainImg"
                        :limit='1'
                        :file-list="mianList"
                        :action="uploadPicLimit"
                        :headers={Authorization:token}
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemovemian"
                        :on-exceed="handlemian"
                        :before-upload="beforeAvatarUpload"
                        :on-success="handlemainsuccess"
                        :on-change="handleChangemian"
                       
                        >
                        <i class="el-icon-plus"></i>
                        </el-upload>
                </div>
                <!-- http://192.168.3.71:8013/api/pic/uploadPic -->
                <!-- https://jsonplaceholder.typicode.com/posts/ -->
                <div style="float:left;">
                        <div style="margin-bottom: 20px;">请上传不大于5张尺寸为750*512的图片,大小为150K以内</div>
                        <el-upload
                      
                        ref="uploadImg"
                        :limit='5'
                        
                        :file-list="fileList"
                        :action="uploadPicLimit"
                        :headers={Authorization:token}
                        list-type="picture-card"
                        
                        :on-remove="handleRemove"
                        :on-exceed="handleexceed"
                        
                        :on-success="handleAvatarSuccess"
                        
                        >
                        <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                </div>
                
            </div>
            <div>
                <el-form :model="form" :rules="rules"  ref="form" label-width="80px">
                    <el-form-item label="商品名称" prop="name">
                        <el-input v-model="form.name" placeholder="商品名称支持50个字符以内" style="width:400px;"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="price">
                        <el-input v-model="form.price" placeholder="支持两位小数，如100.99" style="width:250px;" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="计量单位" prop="unit">
                        <el-input v-model="form.unit" placeholder="如：坛，斤等" style="width:200px;"></el-input>
                    </el-form-item>
                    <el-form-item label="总库存量" prop="inventory">
                         <!-- <el-input v-model="form.inventory" placeholder="请输入总库存量(正整数)" style="width:200px;" type="number"></el-input> -->
                        <el-input-number v-model="form.inventory" @change="handleChange" :min="1" label="描述文字" style="width:250px;"></el-input-number>
                    </el-form-item>
                </el-form>
            </div>
            <div>
                <!-- <div class="title">生产信息</div> -->
                <p class="info">商品规格：如果默认规格不符合您实际需要，可进行编辑</p>
                <el-form  :model="datalist" label-width="120px" :inline="true" >
                       
                       <div class="clearfix">
                            <div style="float:left"  v-for="(item,index) in datalist.items"  :key="index" v-if="item.status">
                                    <el-form-item  >
                                        <el-input v-model="item.name" ></el-input>
                                    </el-form-item>
                                    <input type="text" class="dec"  v-model="item.content" placeholder="请输入规格内容">
                                   
                                    <i class="el-icon-remove-outline" style="margin-right:50px;font-size:20px;"  @click="del(index)"></i>
                                    <!-- <span v-if="item.content == '' || item.name == ''" style="color:red">请填写信息</span> -->
                            </div>
                            <!-- <i class="el-icon-circle-plus-outline" style="margin-right:50px;font-size:20px;" @click="add"></i> -->
                        </div>
                        <el-button type="primary" @click="add">添加</el-button>
                        <div >
                          <!-- <i class="el-icon-circle-plus-outline" style="margin-right:50px;font-size:20px;" @click="add"></i> -->
                        </div>
                    
                </el-form>
                
        
            </div>
        
               
        </el-card>
        <el-card shadow="never" style="margin-top:20px;">
                <div class="title">生产信息</div>
                <p class="info">生产信息：如果默认规则不符合您实际需要，可进行编辑</p>
                <el-form  :model="generate" label-width="120px" :inline="true" >
                       
                    <div class="clearfix">
                         <div style="float:left"  v-for="(item,index) in generate.items"  :key="index" v-if="item.status">
                                 <el-form-item  >
                                     <el-input v-model="item.name" :placeholder="item.name"></el-input>
                                 </el-form-item>
                                 <input type="text" class="dec"  v-model="item.content" placeholder="请输入规格内容">
                                 
                                 <i class="el-icon-remove-outline" style="margin-right:50px;font-size:20px;"  @click="generateDel(index)"></i>
                         </div>
                         <!-- <i class="el-icon-circle-plus-outline" style="margin-right:50px;font-size:20px;" @click="add"></i> -->
                     </div>
                     <el-button type="primary" @click="generateAdd">添加</el-button>
                     <div >
                       <!-- <i class="el-icon-circle-plus-outline" style="margin-right:50px;font-size:20px;" @click="add"></i> -->
                     </div>
                 
             </el-form>
                <div class="clearfix" style="margin-top:30px;">
                    <!-- <quill-editor 
                    class="quill-editor"
                    v-model="describe" 
                    ref="myQuillEditor" 
                    :options="editorOption" 
                    @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
                    @change="onEditorChange($event)"
                    >
                </quill-editor> -->
                <div>
                        <!-- 图片上传组件辅助-->
                        <el-upload
                                class="avatar-uploader"
                                :action="imgUrl"
                                name="file"
                                :headers={Authorization:token}
                                :show-file-list="false"
                                :on-success="uploadSuccess"
                                :on-error="uploadError"
                                :before-upload="beforeUpload"
                                >
                        </el-upload>
                        <!--富文本编辑器组件-->
                       <el-row v-loading="quillUpdateImg">
                        <quill-editor
                                v-model="describe"
                                ref="myQuillEditor"
                                :options="editorOption"
                                @change="onEditorChange($event)"
                                @ready="onEditorReady($event)"
                        >
                        </quill-editor>
                       </el-row>
                    </div>
                <div id="editorElem">
                    </div>
                </div>
              <div style="margin:50px 0px 20px">
                    <el-form>
                        <el-form-item label="状态">
                            <!-- <el-radio v-model="form.state" label="0">上架审核</el-radio> -->
                            <el-radio v-model="form.state" label="2">已下架</el-radio>
                        </el-form-item>
                    </el-form>
              </div>
             

        </el-card>
        <el-button type="primary" style="margin: 20px 0 100px;" @click="submitClick('form')">提交</el-button>
        
       
    </div>
</template>
<script>
 import { quillEditor } from 'vue-quill-editor'

export default {
    data() {
    return {
        uillUpdateImg:false,
        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
        imgUrl:'',
        uploadPicLimit:'',
        token:localStorage.getItem("token"),
        fileList:[],
        mianList:[],
        hide:true,
        off:true,
        imageUrl: '',
        dialogImageUrl: '',
        dialogVisible: false,
        form:{
            name:'',
            price:'',
            unit:'',
            inventory:0,
            state:'2',
            productType:2,
            describe:null,
            specInfo:[],
            createInfo:[],
            mainPic:'',
            listPic:'',//轮播图片
            goodsNo:this.$route.query.goodsNo
           
        },
        imgList:[],
        lunpic:[], //轮播图
        rules: {
          name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 50个字符', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '输入商品价格', trigger: 'change'}
          ],
          
          unit: [
            { type: 'string', required: true, message: '请输入计量单位', trigger: 'change' }
          ],
          inventory: [
            { required: true, message: '请输入总库存量', trigger: 'change' },
           
          ],
         
        },
        state:'0',
        productType:2,
        describe: '',
        specInfo:[],
        createInfo:[],
        
        index: 1,
        
        datalist:{
            items: [
                    {
                        name: '度数',
                        content:'',
                        index: 1,
                        status: 1,
                       
                    },
                    {
                        name: '净含量',
                        content:'',
                        index: 1,
                        status: 1,
                       
                    },
                    {
                        name: '香型',
                        content:'',
                        index: 1,
                        status: 1,
                       
                    },
                    {
                        name: '规格',
                        content:'',
                        index: 1,
                        status: 1,
                      
                    }
                ],
        },
        gindex:1,
        generate:{
            items: [
                    {
                        name: '原料',
                        content:'',
                        index: 1,
                        status: 1,
                       
                    },
                    {
                        name: '酿造工艺',
                        content:'',
                        index: 1,
                        status: 1,
                       
                    },
                    {
                        name: '产地',
                        content:'中国 浙江 温州',
                        index: 1,
                        status: 1,
                       
                    },
                    {
                        name: '产品标准',
                        content:'GB/T10781.3',
                        index: 1,
                        status: 1,
                      
                    },
                    {
                        name: '生产许可证',
                        content:'QS330015016515',
                        index: 1,
                        status: 1,
                       
                    },
                    {
                        name: '生产日期',
                        content:'',
                        index: 1,
                        status: 1,
                        
                    },
                    {
                        name: '批号',
                        content:'',
                        index: 1,
                        status: 1,
                        
                    },
                    {
                        name: '生产厂家',
                        content:'',
                        index: 1,
                        status: 1,
                       
                    },
                    {
                        name: '窖藏条件',
                        content:'避光，潮湿常温10-25°',
                        index: 1,
                        status: 1,
                       
                    }
                ],
        },
        content:null,
        editorOption:{
            modules:{
                    toolbar:{
                        container:[
                        ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
                        ['blockquote','image'],
                        [{ 'header': 1 }, { 'header': 2 }],
                        [{ 'size': ['small', false, 'large', 'huge'] }], 
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                        [{ 'color': [] }], 
                        
                      ],
                      handlers: {
                            'image': function (value) {
                            if (value) {
                                // 触发input框选择图片文件
                                document.querySelector('.avatar-uploader input').click()
                            } else {
                                this.quill.format('image', false);
                            }
                            }
                        }

                    }
                }

        },
        goodsNo:this.$route.query.goodsNo,
        
        }
        
    },
    wacth:{
        "$route":function(to,from){
            // console.log(this.$router)
      //from 对象中包含当前地址
      //to 对象中包含目标地址
      //其实还有一个next参数的，这个参数是控制路由是否跳转的，如果没写，可以不用写next()来代表允许路由跳转，如果写了就必须写next(),否则路由是不会生效的。
        }

    },
    computed: {
        
    },
    methods: {
        baseUrl(){
                let [isTest, href] = [null, window.document.location.href];
                if (href.indexOf("192.168") > -1 || href.indexOf("localhost") > -1 || href.indexOf("36.7") > -1) {
                isTest = true
                } else {
                isTest = false
                }
                if(isTest){
                   this.imgUrl =  'http://192.168.3.71:8013/api/pic/uploadPic'  
                }else{
                    this.imgUrl = 'http://hd4.wsloan.com/timestore/api/pic/uploadPic' 
                }
        }, 
        //限制大小
        PicLimit(){
                let [isTest, href] = [null, window.document.location.href];
                if (href.indexOf("192.168") > -1 || href.indexOf("localhost") > -1 || href.indexOf("36.7") > -1) {
                isTest = true
                } else {
                isTest = false
                }
                if(isTest){
                   this.uploadPicLimit =  'http://192.168.3.71:8013/api/pic/uploadPicLimit'  
                }else{
                    this.uploadPicLimit = 'http://hd4.wsloan.com/timestore/api/pic/uploadPicLimit' 
                }
        }, 
         // 上传图片前
         beforeUpload(res, file) {
                this.quillUpdateImg = true
            },
            // 上传图片成功
            uploadSuccess(res, file) {
                let quill = this.$refs.myQuillEditor.quill;
                if(res.code === 0){
                    let length = quill.getSelection().index;
                    quill.insertEmbed(length, 'image', res.data)
                    quill.setSelection(length + 1)
                    this.quillUpdateImg = false;
                }
                console.log(res)
            },
            // 上传图片失败
            uploadError(res, file) {
                this.quillUpdateImg = false;
            },
            onEditorReady(){},
            onEditorChange({editor, html, text}){
                
                this.describe = html;
                // this.form.describe = html;
        },
        initArr(list){
            // console.log(list,"list")
            this.wangEditor = require("wangeditor");
            var editor = new this.wangEditor("#editorElem");
            editor.customConfig.onchange = html => {
                console.log(html)
                // Vue.set(list, "content", html);
            };
            editor.customConfig.zIndex = 100;
            editor.customConfig.uploadImgShowBase64 = true;
            editor.customConfig.showLinkImg = false;
            editor.customConfig.menus = [
                "head", // 标题
                "bold", // 粗体
                "italic", // 斜体
                "underline", // 下划线
                "strikeThrough", // 删除线
                "foreColor", // 文字颜色
                // "backColor", // 背景颜色
                "link", // 插入链接
                "list", // 列表
                "justify", // 对齐方式
                // "quote", // 引用
                // "emoticon", // 表情
                "image", // 插入图片
                // "table", // 表格
                // "code", // 插入代码
                "undo", // 撤销
                "redo" // 重复
            ];
            editor.create();
            editor.txt.html(list.describe);
            
        },
        handlemian(){
            console.log(123)
            this.$message({
                  type: "error",
                  message: "最多可上传1张"
             });
        },
        handlemainsuccess(res, file){
            console.log(res)
            if(res.code === 0){
                this.form.mainPic = res.data;
            }else{
                this.$message({
                  type: "error",
                  message: res.msg
             }); 
             this.mianList = []
            }
            // let  v = this.$refs['mainImg'].uploadFiles[0].raw
           
            // const fd = new FormData();
            // fd.append('file',v);
        },
        handleChangemian(){

        },
        handleRemovemian(mianList){
            //主图
            console.log(123)
            this.form.mainPic = '';
            console.log(mianList,'222')

            // this.mianList.push({
            //     name:mianList.name,
            //     url:mianList.url
            // })
           
        },
        handleRemove(file,fileList) {
            // this.lunpic = fileList
            //轮播图
            // this.form.listPic = ''
            // this.imgList.remove()
            // console.log('123')
            // console.log(file);
            console.log(file,'file')
            console.log('f',fileList)
            console.log(this.imgList,'this.imglist')
            
            // this.imgList.forEach((element,index)=>{
            //     if(element == file.response.data){
            //         this.imgList.remove(index)
            //     }
            // })
            // this.form.listPic = this.imgList.join(',');
            // console.log(this.imgList,'this.imglist333')
            // this.imgList = fileList
            if(this.$route.query.id == 1){
            this.imgList.forEach((element,index)=>{
                if(element == file.url){
                    console.log(123)
                    this.imgList.remove(index)
                }
            })
            this.form.listPic = this.imgList.join(',');
            console.log(this.form.listPic)
            }else{
                  this.imgList.forEach((element,index)=>{
                        if(element == file.response.data){
                            this.imgList.remove(index)
                        }
                    })
                    this.form.listPic = this.imgList.join(',');
                    // console.log(this.imgList,'this.imglist333')
                    // this.imgList = fileList
            }
        },
        handleexceed(file, fileList){
            this.$message({
                  type: "error",
                  message: "最多可上传5张"
             });
             console.log(file, fileList);
             console.log(this.fileList)
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleAvatarSuccess(res,fileList) {
            //轮播图
            // this.form.listPic = res.data;
            if(res.code === 0){
                this.imgList.push(fileList.response.data);
                this.form.listPic = this.imgList.join(',');
            }else{
                this.$message({
                  type: "error",
                  message: res.msg
             }); 
             this.fileList = [];
            }
           
           
            // console.log(this.form.listPic)
            // let str = this.imgList.join(',')
            // console.log(str,'join')
        },
        
        handleChangeimg(fileList){
            // console.log(fileList,'123')

        },
        beforeAvatarUpload(file) {
       
        //  console.log(fd)
        // const isJPG = file.type === 'image/jpeg';
        // const isLt2M = file.size / 1024 / 1024 < 2;

        //     if (!isJPG) {
        //     this.$message.error('上传头像图片只能是 JPG 格式!');
        //     }
        //     if (!isLt2M) {
        //     this.$message.error('上传头像图片大小不能超过 2MB!');
        //     }
        //     return isJPG && isLt2M;
            
        },
        
      handleChange(value) {
        console.log(value);
      },
      
        
        del(index){
          
            
            if(this.datalist.items.length > 1){
                this.datalist.items[index].status = 0;
                this.datalist.items.remove(index);
                
               
            }else{
                console.log('啦啦')
                this.$message({
                        type: 'error',
                        message: '不可删除'
                })
            }
            // var len = this.datalist.item.length;
            // while (len--) {
            //     this.datalist.items.splice(this.datalist.item[len])
            // }
            // this.datalist.items.splice(index)
            // this.datalist.items.pop({
            //     name: '',
            //     index: this.index,
            //     status: 1,
            //     content:''
            // })

            console.log(this.datalist.items)
            
            // console.log(123)
        },
        add(){
            this.index++;
            this.datalist.items.push({
                name: '',
                index: this.index,
                status: 1,
                content:''
            });
            console.log(this.datalist)
            
           
        },
        generateDel(index){
            if(this.generate.items.length > 1){
                this.generate.items[index].status = 0;
                this.generate.items.remove(index);
                
               
            }else{
                
                this.$message({
                        type: 'error',
                        message: '不可删除'
                })
            }
        },
        generateAdd(){
            this.gindex++;
            this.generate.items.push({
                name: '',
                index: this.gindex,
                status: 1,
                content:''
            });
        },
        onEditorBlur(list){//失去焦点事件
            // console.log(Number(this.describe.length))
            // console.log(list)
        },
        onEditorFocus(list){//获得焦点事件
            // console.log(list)
        },
        onEditorChange(list){//内容改变事件
            
            // console.log(Number(this.describe.length))
            // console.log(list)
        },
        async initAdd(){
            let form = JSON.stringify(this.form);
            let {data} = await this.$post({
                api:'/api/goods/addGoods',
                ContentType: 'application/json',
                isFormData: true,
                data: {
                    ...this.form
                }
            });
            if(data.code === 0){
                this.$message({
                        type: 'success',
                        message: '商城商品添加成功'
                 })
                 setTimeout(()=>{
                    this.$router.push('/goodmanage');
                 },2000)
               
                
            }else{
                this.$message({
                        type: 'error',
                        message: data.msg
                 })  
            }
        },
        
        submitClick(formName){
            let rules = true

           
            if( this.form.mainPic == ''  ){
                this.$message({
                        type: 'error',
                        message: '商品主图不可为空'
                })
                return rules = false
            }
                   
            if(this.describe == ''){
               
                this.$message({
                        type: 'error',
                        message: '商品编辑内容不可为空'
                    })
                    return rules = false
            }
            this.datalist.items.forEach(element=>{
                    if(element.name == '' || element.content == ''){
                        this.$message({
                            type: 'error',
                            message: '商品规格不可为空'
                        })
                        return rules= false
                    }
            })
            this.generate.items.forEach(element=>{
                if(element.name == '' || element.content == ''){
                    this.$message({
                        type: 'error',
                        message: '生产信息不可为空'
                    })
                    return rules = false
                }
            })

            this.$refs[formName].validate((valid) => {
               
                if (valid) {
                 this.form.specInfo = this.datalist.items;
                 this.form.createInfo =  this.generate.items;
                 this.form.describe = encodeURI(this.describe)
                    console.log(rules)
                 if(rules){
                    if(!this.off){
                        return
                    }
                    setTimeout(()=>{
                        this.off = true
                    },3000)
                    if(this.$route.query.id == 1){
                        this.off = false
                        this.initedit();
                    }else{
                        this.off = false
                        this.initAdd();
                    }
                 }else{
                        
                }
                
                
                } else {
                    this.$message({
                        type: 'error',
                        message: '请填入信息'
                    })
                    return false;
                }
            });
            
           
           
        },
        queryData(){
            
            if(this.$route.query.id == 1){
                this.datalist.items = [];
                this.generate.items = [];
                this.getGoodsByNo();
                
            }
        },
        async getGoodsByNo(){
                let {data} = await this.$post({
                    api:'/api/goods/getGoodsByNo',
                    data:{
                        goodsNo:this.goodsNo
                    }
                })
                if(data.code === 0){
                    
                    const list = data.data;
                    // this.mianList = [ {name: 'f222.jpeg', url: list.mainPic}]
                    // console.log(list,'list')
                    // this.initArr(list)
                    this.form.name = list.name;
                    this.form.price = list.price;
                    this.form.inventory = list.inventory;
                    this.form.unit = list.unit;
                    this.describe = list.describe;
                    this.form.state = list.state + '';
                    list.specInfoJson.forEach(element => {
                        this.datalist.items.push({
                            name: element.name,
                            content:element.content,
                            index: 1,
                            status: 1,
                        })
                    });
                    list.createInfoJson.forEach(element =>{
                        this.generate.items.push({
                            name: element.name,
                            content:element.content,
                            index: 1,
                            status: 1,
                        })
                    })
                    this.mianList = [ {name: 'f222.jpeg', url: list.mainPic}]
                    this.form.mainPic = list.mainPic;
                    
                    if(list.listPic != ''){
                        this.form.listPic = list.listPic;
                        let picList = list.listPic.split(',');
                        picList.forEach((el,index)=>{
                            this.fileList.push({
                                name:index,
                                url:el
                            })
                            this.imgList.push(el)
                        })
                    // this.mianList = [ {name: 'f222.jpeg', url: list.mainPic}]
                    }else{
                        this.form.listPic = list.listPic;
                    }
                   
                    
                    console.log(list.listPic.split(','))
                    // console.log('data',)

                }
         },
        //修改
        async initedit(){
            let form = JSON.stringify(this.form);
            this.form.describe = encodeURI(this.describe)
            let {data} = await this.$post({
                api:'/api/goods/updateGoods',
                ContentType: 'application/json',
                isFormData: true,
                data: {
                    // goodsNo:this.goodsNo,
                    ...this.form
                }
            });
            if(data.code === 0){
                this.$message({
                        type: 'success',
                        message: '商城商品修改成功'
                 })
                 setTimeout(()=>{
                    this.$router.push('/goodmanage');
                 },2000)
               
                
            }else{
                this.$message({
                        type: 'error',
                        message: data.msg
                 })  
            }
        },
        

    },
    mounted () {
        // this.initArr();
        this.baseUrl();
        this.PicLimit();
        this.queryData()
        // JSON.parse(localStorage.getItem("userInfo")).userId
    }
}

</script>
<style scoped lang="scss">
.title{
  color:#409EFF;  
  margin-bottom: 20px;
  font-size:20px;
  font-weight: bold;
}
/* .avatar-uploader  {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
  }
  .el-upload{
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader  {
    border-color: #409EFF;
  }
  .el-upload:hover{
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  } */
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .dec{
    height: 38px;
    border: none;
    width:300px;
    border-bottom: 1px solid #ccc;
    outline:none;
    /* margin-right:50px; */
  }
  .info{
      margin: 20px 0;
  }
.clearfix:after {
content: "";
display: block;
visibility: hidden;
height: 0;
clear: both;
}
.clearfix {
zoom: 1;
}
.quill-editor{
    height:400px;
    margin-bottom: 20px;
}
</style>